using Android.App;
using Android.Content;
using Android.OS;
using AndroidX.Core.App;
using AndroidX.Core.Content;
using Android;
using MauiBuilder.Services;
using System.Timers;

namespace MauiBuilder.Platforms.Android
{
    /// <summary>
    /// Android平台通知服务实现
    /// </summary>
    public class NotificationServicePlatform : INotificationService
    {
        /// <summary>
        /// 通知渠道ID
        /// </summary>
        private const string DefaultChannelId = "DefaultNotificationChannel";
        
        /// <summary>
        /// 定时通知渠道ID
        /// </summary>
        private const string TimedChannelId = "TimedNotificationChannel";
        
        /// <summary>
        /// 通知管理器
        /// </summary>
        private NotificationManager? _notificationManager;
        
        /// <summary>
        /// 定时器
        /// </summary>
        private System.Timers.Timer? _timedNotificationTimer;
        
        /// <summary>
        /// 定时通知配置
        /// </summary>
        private string? _timedTitle;
        private string? _timedMessage;
        private int _timedNotificationCounter = 0;
        
        /// <summary>
        /// 日志管理器
        /// </summary>
        private readonly LogManager _logManager = LogManager.Instance;

        public NotificationServicePlatform()
        {
            Initialize();
        }

        /// <summary>
        /// 初始化通知服务
        /// </summary>
        private void Initialize()
        {
            var context = Platform.CurrentActivity ?? global::Android.App.Application.Context;
            _notificationManager = (NotificationManager?)context.GetSystemService(Context.NotificationService);
            CreateNotificationChannels();
        }

        /// <summary>
        /// 创建通知渠道
        /// </summary>
        private void CreateNotificationChannels()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O && _notificationManager != null)
            {
                // 默认通知渠道
                var defaultChannel = new NotificationChannel(
                    DefaultChannelId,
                    "默认通知",
                    NotificationImportance.Default)
                {
                    Description = "应用的默认通知渠道"
                };
                _notificationManager.CreateNotificationChannel(defaultChannel);

                // 定时通知渠道
                var timedChannel = new NotificationChannel(
                    TimedChannelId,
                    "定时通知",
                    NotificationImportance.High)
                {
                    Description = "定时发送的通知渠道"
                };
                _notificationManager.CreateNotificationChannel(timedChannel);
                
                _logManager.LogInfo("通知渠道创建完成");
            }
        }

        /// <summary>
        /// 发送简单通知
        /// </summary>
        public async Task SendNotificationAsync(string title, string message, int? notificationId = null)
        {
            try
            {
                if (!await CheckNotificationPermissionAsync())
                {
                    _logManager.LogInfo("没有通知权限，无法发送通知");
                    return;
                }

                var context = Platform.CurrentActivity ?? global::Android.App.Application.Context;
                var id = notificationId ?? Random.Shared.Next(1000, 9999);

                // 创建点击意图
                var intent = new Intent(context, typeof(MainActivity));
                intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
                var pendingIntent = PendingIntent.GetActivity(context, 0, intent,
                    PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);

                var notification = new NotificationCompat.Builder(context, DefaultChannelId)
                    .SetContentTitle(title)
                    .SetContentText(message)
                    .SetSmallIcon(global::Android.Resource.Drawable.IcDialogInfo)
                    .SetAutoCancel(true)
                    .SetContentIntent(pendingIntent)
                    .SetPriority(NotificationCompat.PriorityDefault)
                    .Build();

                _notificationManager?.Notify(id, notification);
                _logManager.LogInfo($"通知已发送: {title}");
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"发送通知失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 发送带操作的通知
        /// </summary>
        public async Task SendNotificationWithActionsAsync(string title, string message, 
            Dictionary<string, string>? actions = null, int? notificationId = null)
        {
            try
            {
                if (!await CheckNotificationPermissionAsync())
                {
                    _logManager.LogInfo("没有通知权限，无法发送通知");
                    return;
                }

                var context = Platform.CurrentActivity ?? global::Android.App.Application.Context;
                var id = notificationId ?? Random.Shared.Next(1000, 9999);

                var intent = new Intent(context, typeof(MainActivity));
                intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
                var pendingIntent = PendingIntent.GetActivity(context, 0, intent,
                    PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);

                var builder = new NotificationCompat.Builder(context, DefaultChannelId)
                    .SetContentTitle(title)
                    .SetContentText(message)
                    .SetSmallIcon(global::Android.Resource.Drawable.IcDialogInfo)
                    .SetAutoCancel(true)
                    .SetContentIntent(pendingIntent)
                    .SetPriority(NotificationCompat.PriorityHigh);

                // 添加操作按钮
                if (actions != null)
                {
                    foreach (var action in actions.Take(3)) // 最多3个操作
                    {
                        var actionIntent = new Intent(context, typeof(MainActivity));
                        actionIntent.PutExtra("action", action.Key);
                        var actionPendingIntent = PendingIntent.GetActivity(context, 
                            action.Key.GetHashCode(), actionIntent,
                            PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);
                        
                        builder.AddAction(0, action.Value, actionPendingIntent);
                    }
                }

                _notificationManager?.Notify(id, builder.Build());
                _logManager.LogInfo($"带操作的通知已发送: {title}");
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"发送带操作的通知失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 取消指定通知
        /// </summary>
        public async Task CancelNotificationAsync(int notificationId)
        {
            try
            {
                _notificationManager?.Cancel(notificationId);
                _logManager.LogInfo($"通知已取消: {notificationId}");
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"取消通知失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 取消所有通知
        /// </summary>
        public async Task CancelAllNotificationsAsync()
        {
            try
            {
                _notificationManager?.CancelAll();
                _logManager.LogInfo("所有通知已取消");
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"取消所有通知失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 启动定时通知
        /// </summary>
        public async Task StartTimedNotificationAsync(string title, string message, int intervalSeconds = 5)
        {
            try
            {
                if (_timedNotificationTimer != null)
                {
                    await StopTimedNotificationAsync();
                }

                _timedTitle = title;
                _timedMessage = message;
                _timedNotificationCounter = 0;

                _timedNotificationTimer = new System.Timers.Timer(intervalSeconds * 1000);
                _timedNotificationTimer.Elapsed += OnTimedNotificationElapsed;
                _timedNotificationTimer.AutoReset = true;
                _timedNotificationTimer.Start();

                _logManager.LogInfo($"定时通知已启动，间隔{intervalSeconds}秒");
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"启动定时通知失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 停止定时通知
        /// </summary>
        public async Task StopTimedNotificationAsync()
        {
            try
            {
                _timedNotificationTimer?.Stop();
                _timedNotificationTimer?.Dispose();
                _timedNotificationTimer = null;
                _logManager.LogInfo("定时通知已停止");
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"停止定时通知失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 定时通知触发事件
        /// </summary>
        private async void OnTimedNotificationElapsed(object? sender, ElapsedEventArgs e)
        {
            _timedNotificationCounter++;
            var title = $"{_timedTitle} #{_timedNotificationCounter}";
            var message = $"{_timedMessage} - {DateTime.Now:HH:mm:ss}";
            
            await SendNotificationAsync(title, message, 5000 + _timedNotificationCounter);
        }

        /// <summary>
        /// 检查通知权限
        /// </summary>
        public Task<bool> CheckNotificationPermissionAsync()
        {
            try
            {
                var context = Platform.CurrentActivity ?? global::Android.App.Application.Context;
                
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
                {
                    var permission = ContextCompat.CheckSelfPermission(context, Manifest.Permission.PostNotifications);
                    return Task.FromResult(permission == global::Android.Content.PM.Permission.Granted);
                }
                
                return Task.FromResult(true); // Android 13之前默认有通知权限
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"检查通知权限失败: {ex.Message}");
                return Task.FromResult(false);
            }
        }

        /// <summary>
        /// 请求通知权限
        /// </summary>
        public async Task<bool> RequestNotificationPermissionAsync()
        {
            try
            {
                if (await CheckNotificationPermissionAsync())
                {
                    return true;
                }

                if (Platform.CurrentActivity is AndroidX.Fragment.App.FragmentActivity activity)
                {
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
                    {
                        ActivityCompat.RequestPermissions(activity, 
                            new[] { Manifest.Permission.PostNotifications }, 1001);
                    }
                }
                
                // 等待权限结果（这里简化处理，实际应用中可能需要更复杂的逻辑）
                await Task.Delay(1000);
                return await CheckNotificationPermissionAsync();
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"请求通知权限失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 平台是否支持通知
        /// </summary>
        public bool IsNotificationSupported()
        {
            return true; // Android 始终支持通知
        }
    }
}